<template>
  <transition>
    <div class="car-item" v-show="selfIndex === currentIndex">
      <slot></slot>
    </div>
  </transition>
</template> 

<script>
import { getCurrentInstance, reactive, toRefs, watch } from "@vue/runtime-core";
export default {
  name: "CarItem",
  //slot，可以让用户在car-item组件中插入东西
  setup() {
    const instance = getCurrentInstance();
    const state = reactive({
      selfIndex: instance.vnode.key,
      currentIndex: instance.parent.ctx.currentIndex,
    });
    console.log(instance.vnode);
    watch(
      () => {
        return instance.parent.ctx.currentIndex;
      },
      (val) => {
        state.currentIndex = val;
      }
    );

    const stateAsRefs = toRefs(state);
    return {
      ...stateAsRefs,
    };
  },
};
</script>

<style>
.car-item {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.v-enter-active,
.v-leave-active {
  transition: all 0.3s linear;
}

.v-leave-active {
  /* 没有动画即将要动画的时候 */
  transform: translateX(0);
}
.v-leave-to {
  transform: translateX(-100%);
}

.v-enter-active {
  transform: translateX(100%);
}
.v-enter-to {
  transform: translateX(0);
}

.car-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.car-item video {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>